package com.qxzn.app.page.util;

import android.text.InputFilter;
import android.text.Spanned;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.widget.EditText;
import android.widget.ImageView;

import com.qxzn.app.page.R;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Util {

    public static boolean setHintOrShowPwdBlue(EditText editText, ImageView imageView, boolean originShow) {
        boolean isShow = !originShow;
        if (isShow) {
            editText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            imageView.setImageResource(R.mipmap.icon_pwd_show);
        } else {
            editText.setTransformationMethod(PasswordTransformationMethod.getInstance());
            imageView.setImageResource(R.mipmap.icon_pwd_hint);
        }
        editText.setSelection(editText.getText().length());
        return isShow;
    }

    public static boolean setHintOrShowPwdGray(EditText editText, ImageView imageView, boolean originShow) {
        boolean isShow = !originShow;
        if (isShow) {
            editText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            imageView.setImageResource(R.mipmap.icon_pwd_show_gray);
        } else {
            editText.setTransformationMethod(PasswordTransformationMethod.getInstance());
            imageView.setImageResource(R.mipmap.icon_pwd_hint_gray);
        }
        editText.setSelection(editText.getText().length());
        return isShow;
    }

    public static void setPasswordFilter(EditText editText) {
        editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(16), new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                Pattern p = Pattern.compile("([\\ \\\\\\[\\]!\"#$%&'()*+,-./:;<=>?@^_`{|}~]|[0-9a-zA-Z])+");
                Matcher m = p.matcher(source.toString());
                if (!m.matches()) return "";
                return null;
            }
        }});
        editText.setTransformationMethod(PasswordTransformationMethod.getInstance());
    }
}
